import React from 'react';
import { Table, Tooltip, Tag } from 'antd';
import { InfoCircleOutlined, LinkOutlined, FileTextOutlined } from '@ant-design/icons';
import { buildFileLink, buildCommitLink } from '../../utils/gitUrlUtils';

// 添加自定义样式
const customTooltipStyle = `
.ant-tooltip.custom-tooltip {
    max-width: 400px !important;
}
.ant-tooltip.custom-tooltip .ant-tooltip-content {
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
}
.ant-tooltip.custom-tooltip .ant-tooltip-inner {
    background: #ffffff !important;
    border: none !important;
    outline: none !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
    border-radius: 8px !important;
    padding: 0 !important;
    color: #262626 !important;
    min-height: auto !important;
}
.ant-tooltip.custom-tooltip .ant-tooltip-arrow {
    display: none !important;
}
.ant-tooltip.custom-tooltip .ant-tooltip-arrow::before,
.ant-tooltip.custom-tooltip .ant-tooltip-arrow::after {
    display: none !important;
}

/* 分组表头样式 */
.grouped-header-table .ant-table-thead > tr > th {
    background: linear-gradient(90deg, #fafafa 0%, #f0f0f0 100%) !important;
    border-bottom: 2px solid #d9d9d9 !important;
    font-weight: 600 !important;
    font-size: 14px !important;
    padding: 12px 8px !important;
}

.grouped-header-table .ant-table-thead > tr:first-child > th {
    background: linear-gradient(90deg, #e6f7ff 0%, #bae7ff 100%) !important;
    border-bottom: 2px solid #1890ff !important;
    color: #1890ff !important;
    font-weight: 700 !important;
    font-size: 15px !important;
    text-align: center !important;
    padding: 16px 8px !important;
}

.grouped-header-table .ant-table-thead > tr:last-child > th {
    background: #fafafa !important;
    border-bottom: 1px solid #d9d9d9 !important;
    font-size: 13px !important;
    padding: 10px 8px !important;
}

.grouped-header-table .ant-table-tbody > tr:hover > td {
    background: #f5f5f5 !important;
}

.grouped-header-table .ant-table-tbody > tr > td {
    padding: 12px 8px !important;
    border-bottom: 1px solid #f0f0f0 !important;
}
`;

// 注入样式
if (typeof document !== 'undefined') {
    const styleId = 'custom-tooltip-style';
    if (!document.getElementById(styleId)) {
        const style = document.createElement('style');
        style.id = styleId;
        style.textContent = customTooltipStyle;
        document.head.appendChild(style);
    }
}

// 格式化时间的函数
const formatTime = (timeStr: string): string => {
    if (!timeStr) return '-';

    try {
        // 处理 "Fri Jun 06 10:07:43 CST 2025" 格式
        const date = new Date(timeStr);
        if (isNaN(date.getTime())) return timeStr;

        // 格式化为更易读的格式
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (error) {
        return timeStr;
    }
};

// 毫秒转为“X天X小时X分”（不足1天省略天，不足1小时仅显示“X分”）
const formatDuration = (ms?: number): string => {
    if (ms === undefined || ms === null || ms <= 0) return '-';
    const totalMinutes = Math.floor(ms / 60000);
    const days = Math.floor(totalMinutes / 1440);
    const remMinutesAfterDays = totalMinutes % 1440;
    const hours = Math.floor(remMinutesAfterDays / 60);
    const minutes = remMinutesAfterDays % 60;
    if (days > 0) return `${days}天${hours}小时${minutes}分`;
    if (hours > 0) return `${hours}小时${minutes}分`;
    return `${minutes}分`;
};

interface UnitInfoLike {
    gitRepoUrl?: string;
    defaultBranch?: string;
}

// 构建Git仓库URL的函数（兼容SSH和HTTP格式，支持多种Git平台）
const buildGitUrl = (record: any, unitInfo?: UnitInfoLike | null): string => {
    const filePath: string | undefined = record?.filePath;
    if (!filePath) return '';

    const repoUrl = unitInfo?.gitRepoUrl || '';
    if (!repoUrl) return '';

    const branch = unitInfo?.defaultBranch || 'master';

    // 使用新的工具函数构建文件链接，自动处理SSH到HTTP的转换
    return buildFileLink(repoUrl, filePath, branch, record.startLine, record.endLine);
};

const getColumns = (unitInfo?: UnitInfoLike | null) => [
    {
        title: '基本信息',
        children: [
            {
                title: '包名',
                dataIndex: 'packageName',
                key: 'packageName',
                width: 160,
                render: (packageName: string) => packageName || '-'
            },
            {
                title: '类名',
                dataIndex: 'className',
                key: 'className',
                width: 140,
                render: (className: string) => className || '-'
            },
            {
                title: '方法名',
                dataIndex: 'methodName',
                key: 'methodName',
                width: 160,
                render: (methodName: string, record: any) => {
                    return (
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <span>{methodName}</span>
                            <Tooltip
                                title={
                                    <div style={{
                                        width: '380px',
                                        textAlign: 'left',
                                        backgroundColor: '#ffffff',
                                        padding: '16px',
                                        borderRadius: '8px',
                                        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
                                        border: '1px solid #f0f0f0',
                                        maxHeight: '600px',
                                        overflowY: 'auto'
                                    }}>
                                        {/* 标题 */}
                                        <div style={{
                                            fontSize: '16px',
                                            fontWeight: '600',
                                            marginBottom: '16px',
                                            color: '#1890ff',
                                            borderBottom: '1px solid #f0f0f0',
                                            paddingBottom: '8px',
                                            display: 'flex',
                                            alignItems: 'center'
                                        }}>
                                            <FileTextOutlined style={{ marginRight: '8px', fontSize: '16px' }} />
                                            方法详情
                                        </div>

                                        {/* 基本信息 */}
                                        <div style={{ marginBottom: '16px' }}>
                                            <div style={{
                                                marginBottom: '12px',
                                                padding: '8px',
                                                backgroundColor: '#fafafa',
                                                borderRadius: '4px',
                                                border: '1px solid #f0f0f0'
                                            }}>
                                                <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>方法签名</div>
                                                <div style={{
                                                    fontFamily: 'monospace',
                                                    fontSize: '12px',
                                                    color: '#262626',
                                                    backgroundColor: '#ffffff',
                                                    padding: '6px 8px',
                                                    borderRadius: '4px',
                                                    border: '1px solid #e8e8e8',
                                                    wordBreak: 'break-all'
                                                }}>
                                                    {record.methodSignature || '-'}
                                                </div>
                                            </div>

                                            <div style={{ display: 'flex', gap: '16px', marginBottom: '12px' }}>
                                                <div style={{ flex: 1 }}>
                                                    <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>行号范围</div>
                                                    <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                                                        {(() => {
                                                            const gitUrl = buildGitUrl(record, unitInfo);

                                                            if (gitUrl) {
                                                                return (
                                                                    <a
                                                                        href={gitUrl}
                                                                        target="_blank"
                                                                        rel="noopener noreferrer"
                                                                        style={{
                                                                            color: '#1890ff',
                                                                            textDecoration: 'none',
                                                                            display: 'flex',
                                                                            alignItems: 'center',
                                                                            gap: '4px'
                                                                        }}
                                                                    >
                                                                        <Tag color="blue" style={{ margin: 0, fontSize: '11px', cursor: 'pointer' }}>
                                                                            {record.startLine || '-'}
                                                                        </Tag>
                                                                        <span style={{ color: '#8c8c8c', fontSize: '12px' }}>至</span>
                                                                        <Tag color="blue" style={{ margin: 0, fontSize: '11px', cursor: 'pointer' }}>
                                                                            {record.endLine || '-'}
                                                                        </Tag>
                                                                        <LinkOutlined style={{ fontSize: '12px', marginLeft: '4px' }} />
                                                                    </a>
                                                                );
                                                            } else {
                                                                return (
                                                                    <>
                                                                        <Tag color="blue" style={{ margin: 0, fontSize: '11px' }}>
                                                                            {record.startLine || '-'}
                                                                        </Tag>
                                                                        <span style={{ color: '#8c8c8c', fontSize: '12px' }}>至</span>
                                                                        <Tag color="blue" style={{ margin: 0, fontSize: '11px' }}>
                                                                            {record.endLine || '-'}
                                                                        </Tag>
                                                                    </>
                                                                );
                                                            }
                                                        })()}
                                                    </div>
                                                </div>
                                                <div style={{ flex: 1 }}>
                                                    <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>是否入口</div>
                                                    <Tag color={record.isEntry ? 'green' : 'default'} style={{ margin: 0 }}>
                                                        {record.isEntry ? '是' : '否'}
                                                    </Tag>
                                                </div>
                                            </div>

                                            <div style={{ display: 'flex', gap: '16px' }}>
                                                <div style={{ flex: 1 }}>
                                                    <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>服务类型</div>
                                                    <div style={{ fontSize: '13px', color: '#262626' }}>
                                                        {record.serviceType || '-'}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        {/* 类型识别信息 */}
                                        <div style={{ marginBottom: '16px' }}>
                                            <div style={{
                                                fontSize: '14px',
                                                fontWeight: '600',
                                                marginBottom: '12px',
                                                color: '#52c41a',
                                                borderBottom: '1px solid #f0f0f0',
                                                paddingBottom: '8px',
                                                display: 'flex',
                                                alignItems: 'center'
                                            }}>
                                                <span style={{ marginRight: '8px', fontSize: '16px' }}>🏷️</span>
                                                类型识别信息
                                            </div>

                                            <div style={{ display: 'flex', gap: '16px', marginBottom: '12px' }}>
                                                <div style={{ flex: 1 }}>
                                                    <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>是否接口</div>
                                                    <Tag color={record.interfaceFlag ? 'blue' : 'default'} style={{ margin: 0 }}>
                                                        {record.interfaceFlag ? '是' : '否'}
                                                    </Tag>
                                                </div>
                                                <div style={{ flex: 1 }}>
                                                    <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>是否实现类</div>
                                                    <Tag color={record.implementationClass ? 'green' : 'default'} style={{ margin: 0 }}>
                                                        {record.implementationClass ? '是' : '否'}
                                                    </Tag>
                                                </div>
                                            </div>

                                            <div style={{ marginBottom: '12px' }}>
                                                <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>类类型</div>
                                                <div style={{
                                                    fontSize: '12px',
                                                    color: '#262626',
                                                    padding: '4px 8px',
                                                    backgroundColor: '#f0f9ff',
                                                    borderRadius: '4px',
                                                    border: '1px solid #bae7ff',
                                                    display: 'inline-block'
                                                }}>
                                                    {(() => {
                                                        const typeMap: { [key: string]: string } = {
                                                            'INTERFACE': '🔵 接口',
                                                            'IMPLEMENTATION_CLASS': '🟢 实现类',
                                                            'REGULAR_CLASS': '🟡 普通类',
                                                            'ABSTRACT_CLASS': '🟠 抽象类'
                                                        };
                                                        return typeMap[record.classType as string] || record.classType || '-';
                                                    })()}
                                                </div>
                                            </div>

                                            {record.implementedInterfaces && record.implementedInterfaces.trim() !== '' && (
                                                <div style={{ marginBottom: '12px' }}>
                                                    <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>实现的接口</div>
                                                    <div style={{
                                                        fontSize: '12px',
                                                        color: '#262626',
                                                        backgroundColor: '#f6ffed',
                                                        padding: '6px 8px',
                                                        borderRadius: '4px',
                                                        border: '1px solid #b7eb8f',
                                                        wordBreak: 'break-all',
                                                        lineHeight: '1.4'
                                                    }}>
                                                        {record.implementedInterfaces}
                                                    </div>
                                                </div>
                                            )}

                                            {record.parentClass && record.parentClass.trim() !== '' && (
                                                <div>
                                                    <div style={{ fontSize: '12px', color: '#8c8c8c', marginBottom: '4px' }}>父类</div>
                                                    <div style={{
                                                        fontSize: '12px',
                                                        color: '#262626',
                                                        backgroundColor: '#fff7e6',
                                                        padding: '6px 8px',
                                                        borderRadius: '4px',
                                                        border: '1px solid #ffd591',
                                                        wordBreak: 'break-all',
                                                        fontFamily: 'monospace'
                                                    }}>
                                                        {record.parentClass}
                                                    </div>
                                                </div>
                                            )}
                                        </div>

                                        {/* 提示信息 */}
                                        <div style={{
                                            backgroundColor: '#e6f7ff',
                                            padding: '12px',
                                            borderRadius: '6px',
                                            border: '1px solid #bae7ff',
                                            fontSize: '12px',
                                            color: '#0958d9',
                                            display: 'flex',
                                            alignItems: 'center'
                                        }}>
                                            <span style={{ marginRight: '6px', fontSize: '14px' }}>💡</span>
                                            悬停时间字段查看详细修改和调用信息
                                        </div>
                                    </div>
                                }
                                placement="rightTop"
                                overlayStyle={{
                                    maxWidth: '420px',
                                    border: 'none',
                                    background: 'transparent'
                                }}
                                overlayClassName="custom-tooltip"
                                getPopupContainer={(triggerNode) => triggerNode.parentElement || document.body}
                            >
                                <InfoCircleOutlined
                                    style={{
                                        color: '#1890ff',
                                        cursor: 'pointer',
                                        fontSize: '14px'
                                    }}
                                />
                            </Tooltip>

                        </div>
                    );
                }
            }
        ]
    },
    {
        title: '服务信息',
        children: [
            {
                title: '服务类型',
                dataIndex: 'serviceType',
                key: 'serviceType',
                width: 100,
                render: (serviceType: string) => {
                    if (!serviceType) return '-';

                    const typeConfig = {
                        'REST': { text: 'REST', color: 'blue', desc: 'REST接口方法' },
                        'DUBBO': { text: 'DUBBO', color: 'green', desc: 'Dubbo接口方法' },
                        'MAIN': { text: 'MAIN', color: 'orange', desc: 'main方法' },
                        'NONE': { text: 'NONE', color: 'default', desc: '非入口方法' }
                    };

                    const config = typeConfig[serviceType as keyof typeof typeConfig] || { text: serviceType, color: 'default', desc: '' };

                    return (
                        <Tag color={config.color} title={config.desc}>
                            {config.text}
                        </Tag>
                    );
                }
            },
            {
                title: '是否入口',
                dataIndex: 'isEntry',
                key: 'isEntry',
                width: 80,
                render: (isEntry: boolean, record: any) => {
                    // 根据服务类型和isEntry字段来确定显示
                    const serviceType = record.serviceType;
                    let displayValue = isEntry;
                    let color = isEntry ? 'green' : 'default';

                    // 根据后端逻辑，REST、DUBBO、MAIN都是入口方法，NONE是非入口方法
                    if (serviceType === 'REST' || serviceType === 'DUBBO' || serviceType === 'MAIN') {
                        displayValue = true;
                        color = 'green';
                    } else if (serviceType === 'NONE') {
                        displayValue = false;
                        color = 'default';
                    }

                    return (
                        <Tag color={color}>
                            {displayValue ? '是' : '否'}
                        </Tag>
                    );
                }
            }
        ]
    },
    {
        title: '累计无变更时长',
        children: [
            {
                title: () => (
                    <span>
                        📅 无修改时长(天)
                    </span>
                ),
                dataIndex: 'noCodeChangeDurationDays',
                key: 'noCodeChangeDurationDays',
                width: 120,
                sorter: true,
                sortDirections: ['descend', 'ascend'] as any,
                render: (days: number, record: any) => {
                    const displayDays = days !== undefined && days !== null ? `${days}天` : '-';

                    // 构建详细信息tooltip
                    const tooltipContent = (
                        <div style={{
                            width: '280px',
                            textAlign: 'left',
                            backgroundColor: '#ffffff',
                            padding: '16px',
                            borderRadius: '8px',
                            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                            border: '1px solid #f0f0f0'
                        }}>
                            <div style={{
                                fontSize: '14px',
                                fontWeight: '600',
                                marginBottom: '12px',
                                color: '#1890ff',
                                borderBottom: '1px solid #f0f0f0',
                                paddingBottom: '6px'
                            }}>
                                📝 最近修改详情
                            </div>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '60px' }}>修改人：</span>
                                    <span style={{ fontSize: '12px', color: '#262626', fontWeight: '500' }}>
                                        {record.gitLastEditEmp || '-'}
                                    </span>
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '60px' }}>修改时间：</span>
                                    <span style={{ fontSize: '12px', color: '#262626' }}>
                                        {formatTime(record.gitLastEditTime)}
                                    </span>
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '60px' }}>提交ID：</span>
                                    {record.gitLastEditCommitId && unitInfo?.gitRepoUrl ? (
                                        <a
                                            href={buildCommitLink(unitInfo.gitRepoUrl, record.gitLastEditCommitId)}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            style={{
                                                color: '#1890ff',
                                                fontSize: '12px',
                                                fontFamily: 'monospace',
                                                textDecoration: 'underline',
                                                padding: '2px 6px',
                                                backgroundColor: '#f0f9ff',
                                                borderRadius: '4px',
                                                border: '1px solid #bae7ff'
                                            }}
                                        >
                                            {record.gitLastEditCommitId.substring(0, 8)}
                                        </a>
                                    ) : (
                                        <span style={{
                                            fontSize: '12px',
                                            color: '#262626',
                                            fontFamily: 'monospace',
                                            padding: '2px 6px',
                                            backgroundColor: '#f5f5f5',
                                            borderRadius: '4px'
                                        }}>
                                            {record.gitLastEditCommitId ? record.gitLastEditCommitId.substring(0, 8) : '-'}
                                        </span>
                                    )}
                                </div>
                                <div>
                                    <div style={{ color: '#8c8c8c', fontSize: '12px', marginBottom: '4px' }}>提交信息：</div>
                                    <div style={{
                                        fontSize: '12px',
                                        color: '#262626',
                                        backgroundColor: '#f9f9f9',
                                        padding: '8px',
                                        borderRadius: '4px',
                                        border: '1px solid #f0f0f0',
                                        wordBreak: 'break-word',
                                        lineHeight: '1.4'
                                    }}>
                                        {record.gitLastEditMsg || '-'}
                                    </div>
                                </div>
                            </div>
                        </div>
                    );

                    return (
                        <Tooltip
                            title={tooltipContent}
                            placement="topLeft"
                            overlayStyle={{
                                border: 'none',
                                background: 'transparent'
                            }}
                            overlayClassName="custom-tooltip"
                            getPopupContainer={(triggerNode) => triggerNode.parentElement || document.body}
                        >
                            <span style={{ cursor: 'pointer', borderBottom: '1px dashed #1890ff' }}>
                                {displayDays}
                            </span>
                        </Tooltip>
                    );
                }
            }
        ]
    },
    {
        title: 'APM调用信息',
        children: [
            {
                title: 'APM状态',
                dataIndex: 'apmExists',
                key: 'apmExists',
                width: 100,
                sorter: true,
                sortDirections: ['descend', 'ascend'] as any,
                render: (apmExists: boolean | null, record: any) => {
                    // 构建详细信息tooltip
                    const tooltipContent = (
                        <div style={{
                            width: '280px',
                            textAlign: 'left',
                            backgroundColor: '#ffffff',
                            padding: '16px',
                            borderRadius: '8px',
                            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                            border: '1px solid #f0f0f0'
                        }}>
                            <div style={{
                                fontSize: '14px',
                                fontWeight: '600',
                                marginBottom: '12px',
                                color: '#1890ff',
                                borderBottom: '1px solid #f0f0f0',
                                paddingBottom: '6px'
                            }}>
                                📈 APM调用详情
                            </div>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>APM状态：</span>
                                    <span style={{ fontSize: '12px', color: '#262626', fontWeight: '500' }}>
                                        {apmExists === true ? '已发现' : '未发现'}
                                    </span>
                                </div>
                                {apmExists === true && (
                                    <>
                                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                            <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>6个月调用：</span>
                                            <span style={{ fontSize: '12px', color: '#262626' }}>
                                                {record.apmLast6mCount !== null && record.apmLast6mCount !== undefined ? record.apmLast6mCount.toLocaleString() : '0'}
                                            </span>
                                        </div>
                                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                            <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>1年调用：</span>
                                            <span style={{ fontSize: '12px', color: '#262626' }}>
                                                {record.apmLast1yCount !== null && record.apmLast1yCount !== undefined ? record.apmLast1yCount.toLocaleString() : '0'}
                                            </span>
                                        </div>
                                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                            <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>2年调用：</span>
                                            <span style={{ fontSize: '12px', color: '#262626' }}>
                                                {record.apmLast2yCount !== null && record.apmLast2yCount !== undefined ? record.apmLast2yCount.toLocaleString() : '0'}
                                            </span>
                                        </div>
                                    </>
                                )}
                                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>数据更新：</span>
                                    <span style={{ fontSize: '12px', color: '#262626' }}>
                                        {record.apmDataUpdateTime || '-'}
                                    </span>
                                </div>
                            </div>
                        </div>
                    );

                    const getStatusDisplay = () => {
                        if (apmExists === true) {
                            return <Tag color="green">已发现</Tag>;
                        } else {
                            return <Tag color="red">未发现</Tag>;
                        }
                    };

                    return (
                        <Tooltip
                            title={tooltipContent}
                            placement="topLeft"
                            overlayStyle={{
                                border: 'none',
                                background: 'transparent'
                            }}
                            overlayClassName="custom-tooltip"
                            getPopupContainer={(triggerNode) => triggerNode.parentElement || document.body}
                        >
                            <span style={{ cursor: 'pointer' }}>
                                {getStatusDisplay()}
                            </span>
                        </Tooltip>
                    );
                }
            },
            {
                title: '6个月调用',
                dataIndex: 'apmLast6mCount',
                key: 'apmLast6mCount',
                width: 90,
                sorter: true,
                sortDirections: ['descend', 'ascend'] as any,
                render: (count: number, record: any) => {
                    // 根据apmExists状态决定如何显示
                    if (record.apmExists !== true) {
                        return <span style={{ color: '#999' }}>-</span>;
                    } else {
                        return count !== null && count !== undefined ? count.toLocaleString() : '0';
                    }
                }
            },
            {
                title: '1年调用',
                dataIndex: 'apmLast1yCount',
                key: 'apmLast1yCount',
                width: 90,
                sorter: true,
                sortDirections: ['descend', 'ascend'] as any,
                render: (count: number, record: any) => {
                    // 根据apmExists状态决定如何显示
                    if (record.apmExists !== true) {
                        return <span style={{ color: '#999' }}>-</span>;
                    } else {
                        return count !== null && count !== undefined ? count.toLocaleString() : '0';
                    }
                }
            }
        ]
    },
    {
        title: 'SA调用信息',
        children: [
            {
                title: 'SA状态',
                dataIndex: 'saExists',
                key: 'saExists',
                width: 100,
                sorter: true,
                sortDirections: ['descend', 'ascend'] as any,
                render: (saExists: boolean | null, record: any) => {
                    // SA状态判断：只有saExists为true且累计扫描时长大于0且有最后调用时间才算"已发现"
                    const isReallyFound = saExists === true && record.saScannedUptimeMs > 0 && record.lastInvocationTime;

                    // 构建详细信息tooltip
                    const tooltipContent = (
                        <div style={{
                            width: '280px',
                            textAlign: 'left',
                            backgroundColor: '#ffffff',
                            padding: '16px',
                            borderRadius: '8px',
                            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                            border: '1px solid #f0f0f0'
                        }}>
                            <div style={{
                                fontSize: '14px',
                                fontWeight: '600',
                                marginBottom: '12px',
                                color: '#fa8c16',
                                borderBottom: '1px solid #f0f0f0',
                                paddingBottom: '6px'
                            }}>
                                📊 SA调用详情
                            </div>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>SA状态：</span>
                                    <span style={{ fontSize: '12px', color: '#262626', fontWeight: '500' }}>
                                        {isReallyFound ? '已发现' : '未发现'}
                                    </span>
                                </div>
                                {isReallyFound && (
                                    <>
                                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                            <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>首次发现：</span>
                                            <span style={{ fontSize: '12px', color: '#262626' }}>
                                                {record.firstFoundTime || '-'}
                                            </span>
                                        </div>
                                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                            <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>最后调用：</span>
                                            <span style={{ fontSize: '12px', color: '#262626' }}>
                                                {record.lastInvocationTime || '-'}
                                            </span>
                                        </div>
                                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                            <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>无调用时长：</span>
                                            <span style={{ fontSize: '12px', color: '#262626' }}>
                                                {record.noSaCallDurationDays !== undefined && record.noSaCallDurationDays !== null ? `${record.noSaCallDurationDays}天` : '-'}
                                            </span>
                                        </div>
                                        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                            <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>累计扫描时长：</span>
                                            <span style={{ fontSize: '12px', color: '#262626' }}>
                                                {formatDuration(record.saScannedUptimeMs)}
                                            </span>
                                        </div>
                                    </>
                                )}
                                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>数据更新：</span>
                                    <span style={{ fontSize: '12px', color: '#262626' }}>
                                        {record.saDataUpdateTime || '-'}
                                    </span>
                                </div>
                            </div>
                        </div>
                    );

                    const getStatusDisplay = () => {
                        if (isReallyFound) {
                            return <Tag color="green">已发现</Tag>;
                        } else {
                            return <Tag color="red">未发现</Tag>;
                        }
                    };

                    return (
                        <Tooltip
                            title={tooltipContent}
                            placement="topLeft"
                            overlayStyle={{
                                border: 'none',
                                background: 'transparent'
                            }}
                            overlayClassName="custom-tooltip"
                            getPopupContainer={(triggerNode) => triggerNode.parentElement || document.body}
                        >
                            <span style={{ cursor: 'pointer' }}>
                                {getStatusDisplay()}
                            </span>
                        </Tooltip>
                    );
                }
            },
            {
                title: () => (
                    <span>
                        📞 无调用时长(天)
                    </span>
                ),
                dataIndex: 'noSaCallDurationDays',
                key: 'noSaCallDurationDays',
                width: 120,
                sorter: true,
                sortDirections: ['descend', 'ascend'] as any,
                render: (days: number, record: any) => {
                    // 根据SA真实状态决定如何显示：只有saExists为true且累计扫描时长大于0且有最后调用时间才显示数据
                    const isReallyFound = record.saExists === true && record.saScannedUptimeMs > 0 && record.lastInvocationTime;
                    if (!isReallyFound) {
                        return <span style={{ color: '#999' }}>-</span>;
                    }

                    const displayDays = days !== undefined && days !== null ? `${days}天` : '-';

                    // 构建详细信息tooltip
                    const tooltipContent = (
                        <div style={{
                            width: '280px',
                            textAlign: 'left',
                            backgroundColor: '#ffffff',
                            padding: '16px',
                            borderRadius: '8px',
                            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                            border: '1px solid #f0f0f0'
                        }}>
                            <div style={{
                                fontSize: '14px',
                                fontWeight: '600',
                                marginBottom: '12px',
                                color: '#fa8c16',
                                borderBottom: '1px solid #f0f0f0',
                                paddingBottom: '6px'
                            }}>
                                📞 SA调用详情
                            </div>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>无调用时长：</span>
                                    <span style={{ fontSize: '12px', color: '#262626', fontWeight: '500' }}>
                                        {displayDays}
                                    </span>
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>最后调用：</span>
                                    <span style={{ fontSize: '12px', color: '#262626' }}>
                                        {record.lastInvocationTime || '-'}
                                    </span>
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>首次发现：</span>
                                    <span style={{ fontSize: '12px', color: '#262626' }}>
                                        {record.firstFoundTime || '-'}
                                    </span>
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>累计扫描时长：</span>
                                    <span style={{ fontSize: '12px', color: '#262626', fontWeight: '500' }}>
                                        {formatDuration(record.saScannedUptimeMs)}
                                    </span>
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>数据更新：</span>
                                    <span style={{ fontSize: '12px', color: '#262626' }}>
                                        {record.saDataUpdateTime || '-'}
                                    </span>
                                </div>
                            </div>
                        </div>
                    );

                    return (
                        <Tooltip
                            title={tooltipContent}
                            placement="topLeft"
                            overlayStyle={{
                                border: 'none',
                                background: 'transparent'
                            }}
                            overlayClassName="custom-tooltip"
                            getPopupContainer={(triggerNode) => triggerNode.parentElement || document.body}
                        >
                            <span style={{ cursor: 'pointer', borderBottom: '1px dashed #fa8c16' }}>
                                {displayDays}
                            </span>
                        </Tooltip>
                    );
                }
            }
        ]
    },
    {
        title: '废弃分析',
        children: [
            {
                title: '废弃风险等级',
                dataIndex: 'deprecationLevel',
                key: 'deprecationLevel',
                width: 120,
                sorter: true,
                sortDirections: ['descend', 'ascend'] as any,
                render: (level: string, record: any) => {
                    if (!level) return '-';

                    const levelConfig = {
                        'EXTREME_RISK': { text: '极高风险', color: '#ff4d4f', bgColor: '#fff1f0', icon: '🔴' },
                        'HIGH_RISK': { text: '高风险', color: '#fa8c16', bgColor: '#fff7e6', icon: '🟠' },
                        'MEDIUM_RISK': { text: '中等风险', color: '#fadb14', bgColor: '#feffe6', icon: '🟡' },
                        'LOW_RISK': { text: '低风险', color: '#52c41a', bgColor: '#f6ffed', icon: '🟢' },
                        'MINIMAL_RISK': { text: '极低风险', color: '#1890ff', bgColor: '#e6f7ff', icon: '🔵' }
                    };

                    const config = levelConfig[level as keyof typeof levelConfig] ||
                        { text: level, color: '#666', bgColor: '#f5f5f5', icon: '⚪' };

                    // 构建详细信息tooltip
                    const tooltipContent = (
                        <div style={{
                            width: '320px',
                            textAlign: 'left',
                            backgroundColor: '#ffffff',
                            padding: '16px',
                            borderRadius: '8px',
                            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
                            border: '1px solid #f0f0f0'
                        }}>
                            <div style={{
                                fontSize: '14px',
                                fontWeight: '600',
                                marginBottom: '12px',
                                color: config.color,
                                borderBottom: '1px solid #f0f0f0',
                                paddingBottom: '6px',
                                display: 'flex',
                                alignItems: 'center',
                                gap: '6px'
                            }}>
                                <span style={{ fontSize: '16px' }}>{config.icon}</span>
                                废弃分析详情
                            </div>
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>风险等级：</span>
                                    <div style={{
                                        padding: '2px 6px',
                                        borderRadius: '4px',
                                        border: `1px solid ${config.color}`,
                                        backgroundColor: config.bgColor,
                                        color: config.color,
                                        fontSize: '11px',
                                        fontWeight: '500',
                                        display: 'inline-flex',
                                        alignItems: 'center',
                                        gap: '3px'
                                    }}>
                                        <span>{config.icon}</span>
                                        <span>{config.text}</span>
                                    </div>
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>废弃分数：</span>
                                    <span style={{
                                        fontSize: '12px',
                                        color: '#262626',
                                        fontWeight: '600',
                                        padding: '2px 6px',
                                        backgroundColor: '#f0f9ff',
                                        borderRadius: '4px',
                                        border: '1px solid #bae7ff'
                                    }}>
                                        {record.deprecationScore !== null && record.deprecationScore !== undefined ?
                                            `${record.deprecationScore}分` : '-'}
                                    </span>
                                </div>
                                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                    <span style={{ color: '#8c8c8c', fontSize: '12px', minWidth: '80px' }}>更新时间：</span>
                                    <span style={{ fontSize: '12px', color: '#262626' }}>
                                        {record.deprecationUpdateTime || '-'}
                                    </span>
                                </div>
                                <div>
                                    <div style={{ color: '#8c8c8c', fontSize: '12px', marginBottom: '6px' }}>废弃原因：</div>
                                    <div style={{
                                        fontSize: '12px',
                                        color: '#262626',
                                        backgroundColor: '#f9f9f9',
                                        padding: '8px',
                                        borderRadius: '4px',
                                        border: '1px solid #f0f0f0',
                                        wordBreak: 'break-word',
                                        lineHeight: '1.4',
                                        maxHeight: '80px',
                                        overflowY: 'auto'
                                    }}>
                                        {record.deprecationReason || '暂无废弃原因分析'}
                                    </div>
                                </div>
                            </div>
                        </div>
                    );

                    return (
                        <Tooltip
                            title={tooltipContent}
                            placement="topLeft"
                            overlayStyle={{
                                border: 'none',
                                background: 'transparent'
                            }}
                            overlayClassName="custom-tooltip"
                            getPopupContainer={(triggerNode) => triggerNode.parentElement || document.body}
                        >
                            <div style={{
                                padding: '4px 8px',
                                borderRadius: '4px',
                                border: `1px solid ${config.color}`,
                                backgroundColor: config.bgColor,
                                color: config.color,
                                fontSize: '12px',
                                fontWeight: '500',
                                display: 'inline-flex',
                                alignItems: 'center',
                                gap: '4px',
                                cursor: 'pointer'
                            }}>
                                <span>{config.icon}</span>
                                <span>{config.text}</span>
                            </div>
                        </Tooltip>
                    );
                }
            }
        ]
    }
];

interface MethodTableProps {
    data: any[];
    pagination: any;
    loading: boolean;
    onChange: (p: any, f: any, s: any) => void;
    unitInfo?: UnitInfoLike | null;
}

const MethodTable: React.FC<MethodTableProps> = ({ data, pagination, loading, onChange, unitInfo }) => (
    <Table
        rowKey="methodSignature"
        columns={getColumns(unitInfo)}
        dataSource={data}
        loading={loading}
        pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
        }}
        onChange={onChange}
        bordered
        size="middle"
        scroll={{ x: 1700 }}
        style={{
            background: '#fff',
            borderRadius: '8px',
            overflow: 'hidden'
        }}
        className="grouped-header-table"
    />
);

export default MethodTable; 
